<script setup lang="ts">
// 引入Vue的响应式和计算属性工具
import { computed, ref, watch } from 'vue';

// 引入Vben的弹窗和表单工具
import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import { useVbenForm } from '#/adapter/form';
// 引入审核任务相关的API方法
import {
  auditTaskAdd,
  auditTaskInfo,
  auditTaskUpdate,
  auditTaskSubmit,
} from '#/api/aibox/auditTask';

// 引入表单结构定义
import { modalSchema } from './data';

import { message, Upload, Select, Button, Steps, Table } from 'ant-design-vue';
import { InboxOutlined } from '@ant-design/icons-vue';
import { docauditItemList } from '#/api/aibox/docauditItem';
import { modelList } from '#/api/system/model';

// 引入vxe-table相关工具
import { useVbenVxeGrid, vxeCheckboxChecked } from '#/adapter/vxe-table';
import type { VxeGridProps } from '#/adapter/vxe-table';

// 定义自定义事件，供父组件监听刷新
const emit = defineEmits<{ reload: [] }>();

// 是否为编辑模式（true为编辑，false为新增）
const isUpdate = ref(false);
// 动态计算弹窗标题，编辑时显示"编辑"，新增时显示"新增"
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});

// 创建表单实例，绑定表单结构和配置
const [BasicForm, formApi] = useVbenForm({
  commonConfig: {
    // 默认占满两列
    formItemClass: 'col-span-2',
    // label宽度
    labelWidth: 80,
    // 通用配置项，影响所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: modalSchema(),
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});

// 创建弹窗实例，绑定弹窗配置和事件
const [BasicModal, modalApi] = useVbenModal({
  // 弹窗宽度
  class: 'w-[1000px]',
  // 禁用全屏按钮
  fullscreenButton: false,
  // 点击遮罩不关闭弹窗
  closeOnClickModal: false,
  // 启用拖拽功能
  draggable: true,
  // 隐藏默认的取消和确认按钮
  showCancelButton: false,
  showConfirmButton: false,
  // 弹窗打开或关闭时的回调
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    // 打开弹窗时，显示加载状态
    modalApi.modalLoading(true);

    // 获取传入的数据（id）判断是新增还是编辑
    const { id } = modalApi.getData() as { id?: number | string };
    isUpdate.value = !!id;

    // 如果是编辑，获取详情并填充表单
    if (isUpdate.value && id) {
      const record = await auditTaskInfo(id);
      await formApi.setValues(record);
    }

    // 关闭加载状态
    modalApi.modalLoading(false);
  },
});

const currentStep = ref(0);

// 步骤一：上传Word文档
const fileList = ref<any[]>([]);
const uploading = ref(false);
function beforeUpload(file: File) {
  const isWord = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || file.name.endsWith('.docx');
  if (!isWord) {
    message.error('只支持上传Word文档（.docx）');
    return false;
  }
  fileList.value = [file];
  return false;
}
function handleRemove() { fileList.value = []; }
const fileName = computed(() => fileList.value.length ? fileList.value[0].name : '未选择');

// 步骤二：表格多选审核项
const itemList = ref<any[]>([]);
const loadingItems = ref(false);
const selectedRowKeys = ref<string[]>([]);

// vxe-table columns 配置
const vxeColumns: VxeGridProps['columns'] = [
  { type: 'checkbox', width: 60 },
  { title: '审核项名称', field: 'audititemName' },
  { title: '审核章节', field: 'auditChapter' },
  { title: '审核对象', field: 'auditObject' },
  { title: '审核内容', field: 'audititemContent' },
  { title: '状态', field: 'status' },
];

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
  },
  columns: vxeColumns,
  height: 320,
  pagerConfig: { pageSize: 10 },
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        return await docauditItemList({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
      },
    },
  },
  rowConfig: { keyField: 'id' },
  id: 'aibox-auditTask-modal-selectItem',
};

const [VxeTable, vxeTableApi] = useVbenVxeGrid({ gridOptions });

// 步骤切换时，第二步刷新表格
function nextStep() {
  if (currentStep.value === 0 && !fileList.value.length) {
    message.error('请上传Word文档');
    return;
  }
  // 多选校验
  if (currentStep.value === 1 && vxeTableApi.grid.getCheckboxRecords().length === 0) {
    message.error('请选择至少一个审核项');
    return;
  }
  if (currentStep.value < 2) {
    currentStep.value++;
    if (currentStep.value === 1) vxeTableApi.query();
  }
}

// 发起任务时获取选中项
async function handleConfirm() {
  if (!fileList.value.length) { message.error('请上传Word文档'); return; }
  if (vxeTableApi.grid.getCheckboxRecords().length === 0) { message.error('请选择审核项'); return; }
  if (!selectedModel.value) { message.error('请选择大模型'); return; }

  uploading.value = true;
  try {
    const formData = new FormData();
    formData.append('file', fileList.value[0]);
    formData.append('modelName', selectedModel.value);
    formData.append('auditItemIds', vxeTableApi.grid.getCheckboxRecords().map(item => item.id).join(','));

    await auditTaskSubmit(formData);
    message.success('AI审核任务已发起');
    emit('reload');
    modalApi.close();
    fileList.value = [];
    currentStep.value = 0;
  } catch (error) {
    console.error('提交任务失败:', error);
    message.error('提交任务失败');
  } finally {
    uploading.value = false;
  }
}
function handleCancel() {
  modalApi.close();
  fileList.value = [];
  currentStep.value = 0;
}

const columns = [
  { title: '审核项名称', dataIndex: 'audititemName', key: 'audititemName' },
  { title: '审核章节', dataIndex: 'auditChapter', key: 'auditChapter' },
  { title: '审核对象', dataIndex: 'auditObject', key: 'auditObject' },
  { title: '审核内容', dataIndex: 'audititemContent', key: 'audititemContent' },
  { title: '状态', dataIndex: 'status', key: 'status' },
];

// 步骤三：选择大模型
const loadingModels = ref(false);
const modelOptions = ref<{ label: string; value: string }[]>([]);
const selectedModel = ref<string>('');

interface ModelItem {
  modelName: string;
  modelDescribe: string;
}

interface ApiResponse {
  rows?: ModelItem[];
}

// 获取模型列表
async function fetchModelList() {
  try {
    loadingModels.value = true;
    const response = (await modelList({ category: 'chat' })) as ApiResponse;
    const rows = response?.rows ?? [];
    modelOptions.value = rows.map((item: ModelItem) => ({
      label: item.modelDescribe,
      value: item.modelName
    }));
    // 设置默认值为第一个选项（如果有的话）
    if (modelOptions.value.length > 0) {
      selectedModel.value = modelOptions.value[0]?.value ?? '';
    }
  } catch (error) {
    console.error('获取模型列表失败:', error);
    message.error('获取模型列表失败');
  } finally {
    loadingModels.value = false;
  }
}

// 当打开第三步时加载模型列表
watch(() => currentStep.value, (newStep) => {
  if (newStep === 2) {
    fetchModelList();
  }
});

function prevStep() {
  if (currentStep.value > 0) currentStep.value--;
}
</script>

<template>
  <BasicModal :title="'发起AI审核任务'" :close-on-click-modal="false">
    <Steps :current="currentStep" class="mb-6">
      <Steps.Step title="上传文档" />
      <Steps.Step title="选择审核项" />
      <Steps.Step title="选择大模型" />
    </Steps>
    <div v-show="currentStep === 0">
      <div class="border-dashed border-2 border-purple-400 rounded-lg p-6 flex flex-col items-center justify-center min-h-[180px]">
        <div class="mb-2 text-lg font-semibold">Word文档</div>
        <div class="mb-2 text-gray-500">{{ fileName }}</div>
        <Upload.Dragger
          :file-list="fileList"
          :before-upload="beforeUpload"
          :show-upload-list="false"
          :disabled="uploading"
          accept=".docx"
          class="w-full"
        >
          <Button type="primary" :disabled="uploading">上传Word文档</Button>
        </Upload.Dragger>
        <div v-if="fileList.length" class="mt-2">
          <Button type="link" danger @click="handleRemove" :disabled="uploading">重新选择</Button>
        </div>
      </div>
    </div>
    <div v-show="currentStep === 1">
      <div class="mb-2 font-semibold">选择审核项：</div>
      <VxeTable />
    </div>
    <div v-show="currentStep === 2">
      <div class="mb-2 font-semibold">选择大模型类型：</div>
      <Select
        v-model:value="selectedModel"
        :options="modelOptions"
        :loading="loadingModels"
        class="w-full"
        placeholder="请选择大模型"
      />
    </div>
    <div class="flex flex-row justify-end gap-4 mt-6">
      <Button v-if="currentStep > 0" @click="prevStep" :disabled="uploading">上一步</Button>
      <Button v-if="currentStep < 2" type="primary" @click="nextStep" :disabled="uploading">下一步</Button>
      <Button v-if="currentStep === 2" type="primary" @click="handleConfirm" :loading="uploading">确定</Button>
      <Button @click="handleCancel" :disabled="uploading">取消</Button>
    </div>
  </BasicModal>
</template>

<style scoped>
.flex {
  display: flex;
}
.flex-col {
  flex-direction: column;
}
.flex-row {
  flex-direction: row;
}
.gap-4 {
  gap: 1rem;
}
.items-center {
  align-items: center;
}
.justify-center {
  justify-content: center;
}
.justify-end {
  justify-content: flex-end;
}
.min-h-\[180px\] {
  min-height: 180px;
}
.w-full {
  width: 100%;
}
.mt-2 {
  margin-top: 0.5rem;
}
.mb-2 {
  margin-bottom: 0.5rem;
}
.mb-6 {
  margin-bottom: 1.5rem;
}
.p-2 {
  padding: 0.5rem;
}
.p-6 {
  padding: 1.5rem;
}
.rounded-lg {
  border-radius: 0.5rem;
}
.border-dashed {
  border-style: dashed;
}
.border-2 {
  border-width: 2px;
}
.border-purple-400 {
  border-color: #a78bfa;
}
.text-lg {
  font-size: 1.125rem;
}
.font-semibold {
  font-weight: 600;
}
.text-gray-500 {
  color: #6b7280;
}
</style>
